package com.bj58.mis.apm.server.logreceiver.service.impl;

import com.bj58.mis.apm.server.logreceiver.model.HttpAccessStatistic;
import com.bj58.mis.apm.server.logreceiver.repository.HttpAccessStatisticRepository;
import com.bj58.mis.apm.server.logreceiver.service.HttpAccessStatisticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * @author: zhangfx
 * @create: 2018-06-12 16:49
 **/
@Service
@Transactional
public class HttpAccessStatisticServiceImpl implements HttpAccessStatisticService {

    @Autowired
    private HttpAccessStatisticRepository repository;

    @Override
    public void receive(HttpAccessStatistic statistic) {
        HttpAccessStatistic existStatistic = findHttpAccessStatistic(statistic);
        if(existStatistic == null){
            repository.save(statistic);
        } else {
            existStatistic.setRequestCount( existStatistic.getRequestCount() + statistic.getRequestCount());
            existStatistic.setTotalTimeTaken( existStatistic.getTotalTimeTaken() + statistic.getTotalTimeTaken());
            existStatistic.setMaxTimeTaken(Math.max(existStatistic.getMaxTimeTaken(), statistic.getMaxTimeTaken()));
            existStatistic.setMinTimeTaken(Math.min(existStatistic.getMinTimeTaken(), statistic.getMinTimeTaken()));
            existStatistic.setAvgTimeTaken(existStatistic.getTotalTimeTaken()/existStatistic.getRequestCount());
            repository.save(existStatistic);
        }
    }

    private HttpAccessStatistic findHttpAccessStatistic(HttpAccessStatistic statistic){
        HttpAccessStatistic exampleModel = new HttpAccessStatistic();
        exampleModel.setAppName(statistic.getAppName());
        exampleModel.setHostName(statistic.getHostName());
        exampleModel.setRequestTime(statistic.getRequestTime());
        exampleModel.setRequestPath(statistic.getRequestPath());
        exampleModel.setRequestMethod(statistic.getRequestMethod());
        exampleModel.setResponseStatus(statistic.getResponseStatus());

        return repository.findOne(Example.of(exampleModel)).orElse(null);
    }
}
